import React, {Component} from 'react';
import {Row, Col, Table, Button, message, Form, Input, Modal} from 'antd';
import Ajax from "../../util/AjaxUtil";
import './User.less';
import qs from 'qs';
import UserModalForm from './UserInfoForm';

class User extends Component {

    constructor(props) {
        super(props);

        this.state = {
            departmentData: [],
            departmentLoading: false,
            expandedRowKeys: [],
            userTableLoading: false,
            userTableData: [],
            userTablePageSize: 10,
            userTablePageTotal: 0,
            userTablePageNum: 1,
            userModal: {
                type: 'add',
                cancelText: '取消',
                confirmLoading: false,
                destroyOnClose: true,
                okText: '添加',
                visible: false,
                title: '',
                userInfo: null
            }
        };

        this.userForm = null;

    }

    render() {

        const columns = [{
            title: '部门名称',
            dataIndex: 'name',
            key: 'name',
        }];

        const userColumns = [{
            title: '用户名',
            dataIndex: 'username',
            key: 'username',
        }, {
            title: '真实姓名',
            dataIndex: 'realName',
            key: 'realName',
        }, {
            title: '性别',
            dataIndex: 'sex',
            key: 'sex',
            render: (text, record, index) =>{
                if (text===1){
                    return '男';
                }
                if (text===0){
                    return '女';
                }
                return text;
            }
        }, {
            title: '电话',
            dataIndex: 'phone',
            key: 'phone',
        }, {
            title: '邮箱',
            dataIndex: 'email',
            key: 'email',
        }, {
            title: '操作',
            dataIndex: 'action',
            render: (text, record, index) => {
                return (<div>
                    <Button type="primary" size={'small'} className={'action_btn'}
                            onClick={this.openEditUserModal.bind(this, record)}>编辑</Button>
                    <Button type="primary" size={'small'} className={'action_btn'}
                            onClick={this.deleteUser.bind(this, record)}
                    >删除</Button>
                    <Button type="primary" size={'small'}
                            onClick={this.rePassword.bind(this, record)}
                    >重置密码</Button>
                </div>)
            }
        }];

        const {getFieldDecorator} = this.props.form;


        let instance = this;
        return (
            <Row>
                <Col span={4}>
                    <Table loading={this.state.departmentLoading}
                           size={'small'}
                           pagination={false}
                           rowKey={(record) => {
                               return record.id
                           }}
                           dataSource={this.state.departmentData}
                           defaultExpandAllRows={true}
                           expandedRowKeys={this.state.expandedRowKeys}
                           columns={columns}
                           rowClassName={'departmentRow'}
                           onExpand={(expanded, record) => {
                               let expandedRowKeys = [...instance.state.expandedRowKeys];
                               if (expanded) {
                                   expandedRowKeys.push(record.id);
                               } else {
                                   let index = -1;
                                   while ((index = expandedRowKeys.findIndex(key => key === record.id)) !== -1) {
                                       expandedRowKeys.splice(index, 1);
                                   }
                               }
                               instance.setState({expandedRowKeys: expandedRowKeys});
                           }}
                           onRow={(record) => {
                               return {
                                   onClick: (event) => {
                                       let param = instance.props.form.getFieldsValue();
                                       if (param === undefined) {
                                           param = {};
                                       }
                                       param.pageNum = 1;
                                       param.pageSize = instance.state.userTablePageSize;
                                       param.deptId = record.id;
                                       instance.findUserList(param);
                                   }
                               }
                           }}
                    />
                </Col>
                <Col span={20}>
                    <Form style={{marginLeft:5}}>
                        <Row className={"toolbar_action"}>
                            <Col span={8}>
                                <Form.Item label={"用户名"}>
                                    {getFieldDecorator("username")(
                                        <Input size={'small'}/>
                                    )}
                                </Form.Item>
                            </Col>
                            <Col span={8}>
                                <Form.Item label={"手机号"}>
                                    {getFieldDecorator("phone")(
                                        <Input size={'small'}/>
                                    )}
                                </Form.Item>
                            </Col>
                            <Col span={8} style={{paddingTop: 7}}>
                                <Button type="primary" size={'small'} className={"toolbar_action_btn"}
                                        onClick={this.clickFindUserList.bind(this)}>查询</Button>
                                <Button type="primary" size={'small'}
                                        onClick={this.resetForm.bind(this)} className={"toolbar_action_btn"}>重置</Button>
                                <Button type="primary" size={'small'}
                                        onClick={this.openAddUserModal.bind(this)}
                                        className={"toolbar_action_btn"}>添加用户</Button>
                            </Col>
                        </Row>
                        <Row>
                            <Col span={24}>
                                <Table columns={userColumns}
                                       loading={this.state.userTableLoading}
                                       dataSource={this.state.userTableData}
                                       size={'small'}
                                       rowKey={(record) => {
                                           return record.id
                                       }}
                                       pagination={{
                                           current: this.state.userTablePageNum,
                                           pageSize: this.state.userTablePageSize,
                                           size: 'small',
                                           total: this.state.userTablePageTotal,
                                           onChange: (page, pageSize) => {
                                               let param = instance.props.form.getFieldsValue();
                                               if (param === undefined) {
                                                   param = {};
                                               }
                                               param.pageNum = page;
                                               param.pageSize = pageSize;
                                               instance.findUserList(param);
                                           }
                                       }}
                                       className={'userTable'}
                                />
                            </Col>
                        </Row>
                    </Form>
                </Col>
                <Modal cancelText={this.state.userModal.cancelText}
                       confirmLoading={this.state.userModal.confirmLoading}
                       okText={this.state.userModal.okText}
                       title={this.state.userModal.title}
                       visible={this.state.userModal.visible}
                       destroyOnClose={true}
                       onCancel={this.closeUserModal.bind(this)}
                       onOk={this.userInfoModalOkHandle.bind(this)}
                >
                    <UserModalForm userInfo={this.state.userModal.userInfo}
                                   userInfoModalForm={this.userInfoModalForm.bind(this)}
                    />
                </Modal>
            </Row>
        )
    }

    userInfoModalForm(form) {
        this.userForm = form;
    }


    componentDidMount() {
        let instance = this;

        this.setState({
            departmentLoading: true,
            userTableLoading: true
        });
        Ajax.post("/userCenter/department/findAllDepartmentTree")
            .then((response) => {
                let data = [];
                let expandedRowKeys = [];
                data.push(response.data);
                instance.findExpandedRowKeys(response.data, expandedRowKeys);
                instance.setState({
                    departmentData: data,
                    departmentLoading: false,
                    expandedRowKeys: expandedRowKeys
                });
            })
            .catch((error) => {
                message.error("获取数据失败");
            });

        this.findUserList({
            pageSize: this.state.userTablePageSize,
            pageNum: 1
        });
    }

    clickFindUserList() {
        let param = this.props.form.getFieldsValue();
        if (param === undefined) {
            param = {};
        }
        param.pageNum = 1;
        param.pageSize = this.state.userTablePageSize;
        this.findUserList(param);
    }

    findUserList(param) {
        let instance = this;
        Ajax.post("/userCenter/user/findPage", qs.stringify(param))
            .then((response) => {
                instance.setState({
                    userTableLoading: false,
                    userTableData: response.data.list,
                    userTablePageTotal: response.data.total,
                    userTablePageNum: response.data.pageNum
                });
            })
            .catch((error) => {
                message.error("获取数据失败");
            });
    }

    findExpandedRowKeys(data, expandedRowKeys) {
        if (data.children && data.children.length > 0) {
            expandedRowKeys.push(data.id);

            data.children.map((item, key, map) => {
                this.findExpandedRowKeys(item, expandedRowKeys);
                return item;
            });
        }
    }

    resetForm() {
        this.props.form.setFields({"username": null, "phone": null});
        this.findUserList({pageNum: 1, pageSize: this.state.userTablePageSize});
    }

    openAddUserModal() {
        this.setState({
            userModal: {
                type: 'add',
                cancelText: '取消',
                okText: '添加',
                visible: true,
                title: '添加用户'
            }
        });
    }

    openEditUserModal(record) {
        this.setState({
            userModal: {
                type: 'edit',
                cancelText: '取消',
                okText: '修改',
                visible: true,
                title: '修改用户信息',
                userInfo: record
            }
        });
    }

    closeUserModal() {
        this.setState({
            userModal: {
                visible: false,
                userInfo: null
            }
        });
    }

    userInfoModalOkHandle(){
        if (this.state.userModal.type==='add'){
            this.addUser();
        } else if (this.state.userModal.type==='edit'){
            this.editUser();
        }
    }

    addUser(){
        let instance=this;
        this.userForm.validateFields((errors, values) =>{
            if (!errors){
                Ajax.post("/userCenter/user/addUser",qs.stringify(values))
                    .then((response)=>{
                        if (response.data.result){
                            message.success("添加用户成功");
                            instance.setState({
                                userModal:{
                                    visible:false
                                }
                            });
                            instance.componentDidMount();
                        } else {
                            message.error("添加用户失败");
                        }
                    })
                    .catch((error)=>{
                        message.error("添加用户失败");
                    })
            }
        });
    }

    editUser(){
        let instance=this;
        this.userForm.validateFields((errors, values) =>{
            if (!errors){
                values.id=instance.state.userModal.userInfo.id;
                Ajax.post("/userCenter/user/updateUser",qs.stringify(values))
                    .then((response)=>{
                        if (response.data.result){
                            message.success("编辑用户成功");
                            instance.setState({
                                userModal:{
                                    visible:false
                                }
                            });
                            instance.componentDidMount();
                        } else {
                            message.error("编辑用户失败");
                        }
                    })
                    .catch((error)=>{
                        message.error("编辑用户失败");
                    })
            }
        });
    }


    deleteUser(record){
        let instance = this;
        Modal.confirm({
            cancelText:"取消",
            content:"是否删除用户"+record.username+"?",
            okText:"删除",
            onOk:(close)=>{
                Ajax.post("/userCenter/user/deleteUser", qs.stringify({
                    id: record.id
                }))
                    .then((response) => {
                        if (response.data.result) {
                            message.success("删除成功");
                            instance.componentDidMount();
                            close();
                        } else {
                            message.error(response.data.message);
                        }
                    })
                    .catch((error) => {
                        message.error("删除失败")
                    });
            }
        });
    }

    rePassword(record){
        let instance = this;
        Modal.confirm({
            cancelText:"取消",
            content:"是否重置用户"+record.username+"的密码?",
            okText:"重置",
            onOk:(close)=>{
                Ajax.post("/userCenter/user/rePassword", qs.stringify({
                    id: record.id
                }))
                    .then((response) => {
                        if (response.data.result) {
                            message.success("重置密码成功");
                            instance.componentDidMount();
                            close();
                        } else {
                            message.error(response.data.message);
                        }
                    })
                    .catch((error) => {
                        message.error("重置密码失败")
                    });
            }
        });
    }
}

export default Form.create()(User);